<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageData.rows"
              highlight-current-row
              v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>

      <el-table-column prop="name" label="名称" width="220" sortable>
      </el-table-column>

      <el-table-column prop="sn" label="编码" width="180" sortable>
      </el-table-column>

      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="query.currentPage"
                     :page-size="query.pageSize" :total="pageData.totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增和编辑对话框-->
    <!--:close-on-click-modal="false" 点击模态框以外的地方不能关闭模态框-->
    <el-dialog :title="title"
               :visible.sync="roleFormVisible"
               :close-on-click-modal="false">
      <!--ref="roleForm" 指定表单名称，以后可以通过this.$refs.roleForm-->
      <el-form :model="role"
               label-width="80px"
               :rules="roleFormRules"
               ref="roleForm">

        <el-form-item label="名称" prop="name">
          <el-input v-model="role.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="角色编码" prop="sn">
          <el-input v-model="role.sn" auto-complete="off"></el-input>
        </el-form-item>

        <!--
          placeholder="试试搜索：指南"  提示语
          :props="{ multiple: true }"  多选
        -->
        <el-form-item label="分配菜单" prop="menus">
          <el-cascader v-model="role.menus" clearable
                       @change="test"
                       placeholder="试试搜索：指南"
                       :options="menuTree"
                       :props="{
									multiple: true,
								 	label:'name',
									value:'id'
								 }" filterable></el-cascader>
        </el-form-item>

        <el-form-item label="分配权限" prop="permissions">
          <el-select v-model="role.permissions" multiple placeholder="请选择">
            <el-option
                v-for="item in permissionList"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="roleLoading">保存</el-button>
      </div>

    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      //1.新增和编辑的标题
      title: '',

      //2.分页查询的相关参数
      pageData: {
        totals: 0,//分页条
        rows: []//数据表格
      },

      //3.高级查询的相关参数
      query: {
        keyword: '',
        currentPage: 1,//分页条
        pageSize: 5 //分页条
      },

      //4.加载框默认关闭
      listLoading: false,

      //5.批量删除选中项的相关参数
      sels: [],//列表选中列

      //6.编辑界面默认不显示
      roleFormVisible: false,

      //7.保存加载框默认关闭
      roleLoading: false,

      //8.表单校验规则
      roleFormRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        sn: [
          {required: true, message: '请输角色编码', trigger: 'blur'}
        ],
        menus: [
          {required: true, message: '请分配菜单', trigger: 'blur'}
        ],
        permissions: [
          {required: true, message: '请分配权限', trigger: 'blur'}
        ],
      },

      //9.菜单树
      menuTree: [],

      //10.权限列表
      permissionList: [],

      //11.新增和编辑界面的相关数据
      role: {
        id: null,
        name: '',
        sn: '',
        menus: [[]],
        permissions: []
      }
    }
  },
  methods: {
    //0.
    test(tel){
      console.log(tel)
    },
    //1.
    handleChange(value) {
      this.role.index = value;
    },

    //2.高级查询方法
    search() {
      //修改页码跳转到第一页
      this.query.currentPage = 1;
      //改查询条件=双向绑定输入时自动改变，只需要重新查询一次就ok
      this.getRoles();
    },

    //3.跳转页数查询
    handleCurrentChange(val) {
      //当前页设置为前端传来的参数val
      this.query.currentPage = val;
      //重新获取数据
      this.getRoles();
    },

    //4.获取角色列表
    getRoles() {
      this.listLoading = true; //加载条
      this.$http.post("/role", this.query)
          .then(result => {
            this.pageData = result.data;
            this.listLoading = false; //去除加载条
          })
          .catch(result => {
            this.$message({ //错误提示
              message: result.message,
              type: 'error'
            });
          })

    },

    //5.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let url = "/role/" + row.id;
        this.$http.delete(url)
            .then((result) => {
              result = result.data; //{sucesss:true,message:"xx"}
              this.listLoading = false;
              if (result.success) { //成功提示
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              } else {
                this.$message({ //错误提示
                  message: result.message,
                  type: 'error'
                });
              }
              //重新加载数据
              this.getRoles();
            });
      }).catch(() => {
      });
    },

    //6.显示编辑界面
    handleEdit: function (index, row) {
      //修改对话框标题
      this.title = "修改角色";
      //弹出对话框
      this.roleFormVisible = true;
      //回显数据
      this.role = Object.assign({}, row);
      console.log(row)

      //todo 显示编辑界面里的什么玩意儿
        console.log(row.ownMenus) //[菜单,菜单,菜单]
      if (row.ownMenus) {//需要回显，这里要处已经拥有的权限的格式
        let menus = [];
        //遍历当前角色拥有的菜单
        for (let i = 0; i < row.ownMenus.length; i++) {
          //当前角色拥有的某一个菜单
          let menu = row.ownMenus[i];
          let menuTmp = [];
          //判断当前角色拥有的某一个菜单
          //不是顶级菜单走这里
          if (menu.parent_id != null && menu.parent_id != "") {
            menuTmp.push(menu.parent_id);
          }
          //是顶级菜单直接走这里，或者不是顶级菜单执行完上一步再走这步
          menuTmp.push(menu.id);
          menus.push(menuTmp);
        }

        this.role.menus = menus;  //[[1],[1,11],[1,12], [11,111],[11,112],  [111,1111]]===[[父级id,子id],[父级id,子id],[父级id,子id]]  如果子id为空=这个数组定是父级id
        console.log(this.role.menus)  //[[父级id,子id],[父级id,子id],[父级id,子id]]
      }

    },

    //7.显示新增界面
    handleAdd: function () {
      //修改对话框标题
      this.title = "添加角色";
      //弹出对话框
      this.roleFormVisible = true;
      //置空数据，防止先点修改，后点添加有值
      this.role = {
        id: null,
        name: '',
        sn: '',
        //todo 获取菜单树
        menus: [[]],
        //todo 获取所有权限
        permissions: []
      };

    },

    //8.保存
    save: function () {
      //表单校验
      this.$refs.roleForm.validate((valid) => {
        //如果校验成功
        if (valid) {
          //弹出确认框
          this.$confirm('确认保存吗？', '提示', {}).then(() => {
            //开启加载框
            this.roleLoading = true;
            //复制数据到para对象中
            let para = Object.assign({}, this.role);

            //处理分配菜单参数格式 menus:[[22,23],[22,24],[22,25]]---->menus:[23,24,25]
            // todo 这里原来是将二维数组转换成一维数组
            let menusArr = para.menus;//[[父级id,子id],[父级id,子id],[父级id,子id]]
            if (menusArr) {

              let menusTmp = [];
              for (var i = 0; i < menusArr.length; i++) {
                let menuTmp = menusArr[i];  //[父级id,子id]
                menusTmp.push(menuTmp[menuTmp.length - 1]);  //menuTmp[menuTmp.length - 1]  == 子id
              }
              para.menus = menusTmp;    //[子id,子id,子id]
            }

            // console.log(para);
            // console.log(para.permissions)
            // console.log(para.menus)

            //发送请求
            this.$http.put("/role", para)
                //请求成功回调
                .then((result) => {
                  //关闭加载框
                  this.roleLoading = false;
                  //接收后端返回的数据
                  result = result.data;

                  if (result.success) {
                    this.$message({
                      message: '提交成功',
                      type: 'success'
                    });
                    //关闭对话框
                    this.roleFormVisible = false;
                    //重置表单
                    this.$refs['roleForm'].resetFields();
                    //重新获取数据
                    this.getRoles();
                  } else {
                    this.$message({
                      message: result.message,
                      type: 'error'
                    });
                    //失败了可能修改了提交
                  }
                });
          });
        }
      });
    },

    //9.批量删除当前行的改变
    selsChange: function (sels) {
      this.sels = sels;
    },

    //10.批量删除
    batchRemove: function () {
      //遍历选择记录把id放到一个数组中
      var ids = this.sels.map(item => item.id); //[1,2,3]
      //弹出确认框
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        //开启加载框
        this.listLoading = true;
        //发送请求
        this.$http.patch("/role", ids)
            .then((result) => {
              //关闭加载框
              this.listLoading = false;
              //接收后端返回的数据
              result = result.data;

              if (result.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              }
              //跳转到第一页
              this.handleCurrentChange(1);
            });
      }).catch(() => {

      });
    },

    //11.获取菜单树
    getMenuTree() {
      //发送请求
      this.$http.get("/menu/tree")
          .then(result => {
            if (result.data) {
              //赋值给menuTree
              this.menuTree = result.data;
              // console.log(this.menuTree)
            }
          });
    },

    //12.获取所有权限
    getPermissionList() {
      //发送请求
      this.$http.get("/permission")
          .then(result => {
            if (result.data) {
              //赋值给permissionList
              this.permissionList = result.data;
            }
          });
    }

  },
  mounted() {
    this.getRoles();
    this.getMenuTree();//加载菜单树
    this.getPermissionList();//加载权限下拉列表
  }
}

</script>

<style scoped>

</style>